var util = require('../../libs/util.js');
var app = getApp();
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    warehouseData: [],
    searchShowed: false,
    searchVal: "",
    selected: false,
    currentPage: 1,
    pageNumber: 0,
    pageRows:20,
    firstPageDisabled: true,
    prevPageDisabled: true,
    nextPageDisabled: false,
    lastPageDisabled: false,
    warehouse:''
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  onLoad: function (e) {
    wx.setNavigationBarTitle({ "title": app.appName +"--选择注册的发货点" });
    wx.removeStorage({
      key: 'path_warehouse',
      success: function (res) {
      }
    });
    if(e.user){
      this.setData({
        user:e.user
      })
    }
    if (e.id) {
      this.setData({
        id: e.id
      })
    }
    if (e.warehouse) {
      var _warehouse = e.warehouse;
      if(String(e.warehouse).indexOf("undefined") > -1 || String(e.warehouse).indexOf("null") > -1){
        var warehouse = String(e.warehouse).split(",");
        var new_warehouse = [];
        for(var i=0;i<warehouse.length;i++){
          if(warehouse[i] != 'undefined' && warehouse[i] != 'null'){
            new_warehouse.push(warehouse[i])
          }
        }
        _warehouse = new_warehouse;
      }
      this.setData({
        warehouse: _warehouse
      })
    }
    this.loadData();
  },
  onReady: function () {
    wx.hideToast()
  },
  showSearch: function () {
    this.setData({
      searchShowed: true
    });
  },
  hideSearch: function () {
    this.setData({
      searchVal: "",
      searchShowed: false
    });
    this.loadData();
  },
  clearSearch: function () {
    this.setData({
      searchVal: ""
    });
    this.loadData();
  },
  searchTyping: function (e) {
    this.setData({
      searchVal: e.detail.value
    });
    this.setData({
      currentPage: 1
    });
    this.loadData();
  },
  loadData() {
    wx.showLoading({
      title: '加载数据中...',
    });
    var that = this;
    util.getData("warehouse", {
      CO_ID: app.globalData.CO_ID,
      currentPage: that.data.currentPage,
      sql: that.data.searchVal,
      pageRows: that.data.pageRows
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        var _data = res.data.data[0], _data_ = [], rowNumber = Number(res.data.data[1][0].count);
        that.setData({
          pageNumber: Math.ceil(rowNumber / that.data.pageRows)
        })
        var warehouseData = [];
        if (that.data.warehouse) {
          var selectWarehouse = String(that.data.warehouse).split(",");
        }
        var pageSelectWarehouse = [];
        for (var i = 0; i < _data.length; i++) {
          var _item = { name: _data[i].name, abbreviation: _data[i].abbreviation, address: _data[i].address, value: _data[i].ID }
          if (that.data.warehouse) {
            if (selectWarehouse.indexOf(String(_data[i].ID)) > -1){
              _item = { name: _data[i].name, abbreviation: _data[i].abbreviation, address: _data[i].address, value: _data[i].ID, checked:true };
              pageSelectWarehouse.push(String(_data[i].ID));
            }
          }
          warehouseData.push(_item)
          _data_.push(_item);
        };
        that.setData({
          warehouseData: warehouseData,
          pageSelectWarehouse: pageSelectWarehouse
          //dataFilterList: _data_,
          //dataList: _data_
        })
        that.pageDisabled();
      }
      wx.hideLoading();
    });
  },
  setDataList: function (text) {
    var that = this;
    var data = that.data.dataList, _data_ = [];
    for (var i = 0; i < data.length; i++) {
      if (String(data[i].name).indexOf(text) > -1 || String(data[i].address).indexOf(text) > -1 || String(data[i].ID).indexOf(text) > -1) {
        _data_.push({ name: data[i].name, abbreviation: data[i].abbreviation, address: data[i].address, value: data[i].value });
      }
    };
    that.setData({
      pageNumber: Math.ceil(_data_.length / 20),
      dataFilterList: _data_
    })
  },
  loadPageData: function () {
    var that = this;
    var warehouseData = [];
    var _data = that.data.dataFilterList;
    var currentPage = that.data.currentPage;
    for (var i = 0; i < _data.length; i++) {
      var _item = { name: _data[i].name, abbreviation: _data[i].abbreviation, address: _data[i].address, value: _data[i].ID }
      if (i < currentPage * 20 && i >= (currentPage - 1) * 20) {
        warehouseData.push(_item)
      }
    };
    that.setData({
      warehouseData: warehouseData
    })
  },
  dataSelect: function (e) {
    console.log(e)
    var warehouseData = this.data.warehouseData;
    for (var i = 0; i < warehouseData.length; i++) {
      warehouseData[i].checked = warehouseData[i].value == e.detail.value;
      if (warehouseData[i].value == e.detail.value) {
        wx.setStorage({
          key: "monitor_warehouse",
          data: warehouseData[i]
        });
        this.setData({
          selected: true
        })
      }
    }
    this.setData({
      warehouseData: warehouseData
    });
  },
  multiDataSelect: function (e) {
    var that = this;
    var warehouseData = this.data.warehouseData, values = e.detail.value;
    //已选仓库
    var warehouse = [];
    if (that.data.warehouse != ''){
      warehouse = that.data.warehouse.split(",");
    }
    //当页已选仓库
    var pageSelectWarehouse = that.data.pageSelectWarehouse, _pageSelectWarehouse = [];
    //从已选仓库中删除--去掉勾中时
    if (pageSelectWarehouse.length > 0) {
      for (var j = 0; j < pageSelectWarehouse.length; j++) {
        if (values.indexOf(pageSelectWarehouse[j]) > -1){
          _pageSelectWarehouse.push(pageSelectWarehouse[j])
        } else {
          warehouse = util.arrayDeleteItem(warehouse, pageSelectWarehouse[j]);
        }
      }
    }
    //在已选仓库增加--勾中时
    for (var i = 0, lenI = warehouseData.length; i < lenI; ++i) {
      warehouseData[i].checked = false;

      for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (warehouseData[i].value == values[j]) {
          warehouseData[i].checked = true;
          if (warehouse.indexOf(String(warehouseData[i].value)) == -1){
            warehouse.push(String(warehouseData[i].value));
          }
          break;
        }
      }
    }
    if (warehouse.length > 0) {
      var whData = [];
      for (var i = 0; i < warehouseData.length;i++){
        if (warehouseData[i].checked == true){
          whData.push(warehouseData[i]);
        }
      }
      wx.setStorage({
        key: "monitor_warehouse",
        data: whData
      });
      this.setData({
        selected: true
      })
    }
    this.setData({
      warehouseData: warehouseData,
      warehouse: warehouse.join(",")
    });
    
  },
  confirmData: function () {
    var  that = this;
    if ((that.data.user == 'schedule' || that.data.user == 'operation') && that.data.id){
      wx.showLoading({
        title: '提交中...',
      });
      util.postData("/atapi/user/user/setManageOfProject", {
        id: that.data.id,
        warehouse: that.data.warehouse,
        role:that.data.user,
        phone:app.globalData.phone,
        CO_ID:app.globalData.CO_ID,
        openid:app.globalData.openid,
        unionid:app.globalData.unionid,
        name:app.globalData.truename
      }, function (res, error) {
        console.log(res); console.log(error)
        wx.hideLoading();
        if (res.data.success) {
          wx.showModal({
            title: '温馨提示',
            content: '提交成功。是否返回？',
            success(res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/enterprise/user_'+that.data.user
                })
              }
            }
          })
        }else{
          wx.showToast({
            title: "提交失败",
            image: "/images/wrong.svg",
            duration: 3000
          });
        }
      });
      return false;
    }
    if (that.data.user == 'carrier' && that.data.id) {
      var warehouse = String(that.data.warehouse).split(",");
      wx.showLoading({
        title: '提交中...',
      });
      util.postData("/atapi/carrier/carrier/setManageOfProject", {
        id: that.data.id,
        warehouse: warehouse.join(",")
      }, function (res, error) {
        console.log(res); console.log(error)
        wx.hideLoading();
        if (res.data.success) {
          wx.showModal({
            title: '温馨提示',
            content: '提交成功。是否返回？',
            success(res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/carrier/carrier'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: "提交失败",
            image: "/images/wrong.svg",
            duration: 3000
          });
        }
      });
      return false;
    }
    if (this.data.selected) {
      wx.navigateBack({
        delta: 1
      });
    } else {
      wx.showToast({
        title: "请选择项目",
        image: "/images/wrong.svg",
        duration: 3000
      });
    }
  },
  cancelSelected:function(e){
    wx.setStorage({
      key: "monitor_warehouse",
      data: { name: "全部", abbreviation: "", address: "", value: ""}
    });
    wx.navigateBack({
      delta: 1
    });
  },
  prevPage: function () {
    var currentPage = Number(this.data.currentPage);
    if (currentPage > 1) {
      currentPage--;
    } else {
      currentPage = 1;
    }
    this.setData({
      currentPage: currentPage
    });
    this.pageDisabled();
    this.loadData();
  },
  nextPage: function () {
    var currentPage = Number(this.data.currentPage), pageNumber = this.data.pageNumber;
    if (currentPage < pageNumber) {
      currentPage++;
    } else {
      currentPage = pageNumber;
    }
    this.setData({
      currentPage: currentPage
    });
    this.pageDisabled();
    this.loadData();
  },
  firstPage: function () {
    this.setData({
      currentPage: 1
    });
    this.pageDisabled();
    this.loadData();
  },
  lastPage: function () {
    this.setData({
      currentPage: this.data.pageNumber
    });
    this.pageDisabled();
    this.loadData();
  },
  pageDisabled: function () {
    var currentPage = Number(this.data.currentPage), pageNumber = this.data.pageNumber;
    if (pageNumber == 1) {
      this.setData({
        firstPageDisabled: true,
        prevPageDisabled: true,
        nextPageDisabled: true,
        lastPageDisabled: true
      });
    } else if (currentPage == 1) {
      this.setData({
        firstPageDisabled: true,
        prevPageDisabled: true,
        nextPageDisabled: false,
        lastPageDisabled: false
      });
    } else if (currentPage < pageNumber) {
      this.setData({
        firstPageDisabled: false,
        prevPageDisabled: false,
        nextPageDisabled: false,
        lastPageDisabled: false
      });
    } else if (currentPage == pageNumber) {
      this.setData({
        firstPageDisabled: false,
        prevPageDisabled: false,
        nextPageDisabled: true,
        lastPageDisabled: true
      });
    }
  },
  cancelConfirmData: function () {
    wx.navigateBack({
      delta: 1
    });
  }
});